package eoeProject.edenOfEast.page.registerForm.component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.validator.AbstractValidator;
import org.apache.wicket.validation.validator.EmailAddressValidator;

import eoeProject.edenOfEast.bean.EOEUserBean;
import eoeProject.edenOfEast.core.DBConnector;
import eoeProject.edenOfEast.core.DBUtils;
import eoeProject.edenOfEast.core.EOEAuthenticatedWebSession;
import eoeProject.edenOfEast.core.PassDigest;
import eoeProject.edenOfEast.core.SQLMaker;
import eoeProject.edenOfEast.dataBase.DB_EOE_USER;

public class RegisterFormPanel extends Panel {
	private static final long serialVersionUID = 1L;

	private Form<Void> form = new Form<Void>("form");

	private Model<String> passWord = new Model<String>("");

	private Model<String> passWordConfirm = new Model<String>("");

	private Model<String> userName = new Model<String>("");

	private Model<String> email = new Model<String>("");

	private Model<String> accountTyoe = new Model<String>("");

	private FeedbackPanel feedback = new FeedbackPanel("feedback");

	private Label message = new Label("message", "");

	@SuppressWarnings("unchecked")
	public RegisterFormPanel(String id) {
		super(id);
		feedback.setOutputMarkupId(true);
		message.setOutputMarkupId(true);
		message.setVisible(false);

		List<String> list = new ArrayList<String>();
		list.add("通常アカウントで作成する");
		list.add("twitterアカウントで作成する");
		ListChoice<String> accountTyoeList = new ListChoice<String>(
				"accountTyoe", accountTyoe, list);
		accountTyoeList.setRequired(true);
		form.add(accountTyoeList);
		TextField<String> userNameForm = new TextField<String>("userNameForm",
				userName);
		userNameForm.setRequired(true);
		userNameForm.add(new UserNameValidator());
		form.add(userNameForm);
		PasswordTextField passwordForm = new PasswordTextField("passwordForm",
				passWord);
		passwordForm.add(new PasswordValidator());
		form.add(passwordForm);
		PasswordTextField passwordConfirmForm = new PasswordTextField(
				"passwordConfirmForm", passWordConfirm);
		passwordConfirmForm.add(new PasswordValidator());
		form.add(passwordConfirmForm);
		TextField<String> emailForm = new TextField<String>("emailForm", email);
		emailForm.add(EmailAddressValidator.getInstance());
		emailForm.add(new EmailValidator());
		emailForm.setRequired(true);
		form.add(emailForm);

		form.add(submitButton);
		form.add(feedback);
		form.add(message);
		add(form);

	}

	private AjaxButton submitButton = new AjaxButton("submit") {
		/**
		 *
		 */
		private static final long serialVersionUID = -2942520388218435030L;

		@SuppressWarnings("rawtypes")
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form form) {
			setResponsePage(form.getPage());
			String pass = PassDigest.getInstance().getPassDigest(
					passWord.getObject(), userName.getObject());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			EOEUserBean bean = new EOEUserBean();
			bean.setUserId(DBUtils.getNextId(DB_EOE_USER.TABLE_NAME,
					DB_EOE_USER.PRIMARY_KEY));
			bean.setUserName(userName.getObject());
			bean.setPassword(pass);
			bean.setRole(1);
			bean.setEmail(email.getObject());
			bean.setCreateDate(new Date());
			bean.setUpdateDate(new Date());
			if (accountTyoe.getObject().equals("twitterアカウントで作成する")) {
				bean.setAccountType(1);

			} else
				bean.setAccountType(0);
			SQLMaker sql = new SQLMaker(DB_EOE_USER.TABLE_NAME,
					SQLMaker.SQL_TYPE_INSERT);
			sql.setInsert(bean);
			if (DBConnector.getInstance().set(sql.getSQL())) {
				EOEAuthenticatedWebSession.get().authenticate(
						userName.getObject(), passWord.getObject());
				setResponsePage(new eoeProject.edenOfEast.page.registerFormSuccess.Index());
			} else {
				message = new Label("message", "*登録に失敗しました。");
				message.setOutputMarkupId(true);
				message.setVisible(true);
				form.addOrReplace(message);
			}

		}

		@SuppressWarnings({ "rawtypes" })
		@Override
		protected void onError(final AjaxRequestTarget target, final Form form) {
			target.add(feedback);
		}
	};

	@SuppressWarnings("rawtypes")
	private class PasswordValidator extends AbstractValidator {
		private static final long serialVersionUID = 7638140005191056302L;

		@SuppressWarnings({ "unchecked" })
		@Override
		protected void onValidate(IValidatable validatable) {
			Model<String> str = new Model<String>(validatable.getValue()
					.toString());
			if (passWord.getObject().equals("")) {
				passWord = str;
			} else if (!passWord.getObject().equals(
					validatable.getValue().toString())) {
				error(validatable, "PasswordValidator");
				passWord = new Model<String>("");
			}
			return;
		}
	}

	@SuppressWarnings("rawtypes")
	private class UserNameValidator extends AbstractValidator {
		private static final long serialVersionUID = 7638140005191056302L;

		@SuppressWarnings({ "unchecked" })
		@Override
		protected void onValidate(IValidatable validatable) {
			SQLMaker sql = new SQLMaker(DB_EOE_USER.TABLE_NAME,
					SQLMaker.SQL_TYPE_SELECT);
			sql.addExpEquals(DB_EOE_USER.USER_NAME, validatable.getValue()
					.toString());
			try {
				ResultSet rs = DBConnector.getInstance().get(sql.getSQL());
				if (rs.next()) {
					error(validatable, "UserNameValidator");
				}

			} catch (SQLException e) {
				System.out.println("UserNameValidatorException: "
						+ e.getMessage());
			}
			return;
		}
	}

	@SuppressWarnings("rawtypes")
	private class EmailValidator extends AbstractValidator {
		private static final long serialVersionUID = 7638140005191056302L;

		@SuppressWarnings({ "unchecked" })
		@Override
		protected void onValidate(IValidatable validatable) {
			SQLMaker sql = new SQLMaker(DB_EOE_USER.TABLE_NAME,
					SQLMaker.SQL_TYPE_SELECT);
			sql.addExpEquals(DB_EOE_USER.EMAIL, validatable.getValue()
					.toString());
			try {
				ResultSet rs = DBConnector.getInstance().get(sql.getSQL());
				if (rs.next()) {
					error(validatable, "EmailValidator");
				}

			} catch (SQLException e) {
				System.out
						.println("EmailValidatorException: " + e.getMessage());
			}
			return;
		}
	}

}
